use axum::http::StatusCode;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json;

#[derive(Debug, Serialize, Deserialize)]
pub struct RespVO<T> {
    pub code: u16,
    pub msg: Option<String>,
    pub data: Option<T>,
}

pub const CODE_SUCCESS: StatusCode = StatusCode::OK;
pub const CODE_ERROR: StatusCode = StatusCode::INTERNAL_SERVER_ERROR;

impl<T: DeserializeOwned + Serialize> RespVO<T> {
    pub fn success(msg: Option<String>, data: Option<T>) -> Self {
        Self {
            code: CODE_SUCCESS.as_u16(),
            msg,
            data,
        }
    }

    pub fn err(msg: Option<String>, data: Option<T>) -> Self {
        Self {
            code: CODE_ERROR.as_u16(),
            msg,
            data,
        }
    }
}

impl<T: Serialize> RespVO<T> {
    pub fn to_string(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
    }
}